package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JiLinZhenZeUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * 吉林震泽
 */
@Service
public class JiLinZhenZeApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiCode = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();

        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        long timestamp = System.currentTimeMillis() / 1000;

        TreeMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("app_id", Integer.valueOf(apiCode));
        paramMap.put("timestamp", timestamp);
        paramMap.put("mobile", mobileMd5);
        String sign = SecureUtil.md5(joinKeyValueString(paramMap) + apiSecret).toUpperCase();

        paramMap.put("sign", sign);


        log.info("【吉林震泽】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【吉林震泽】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);

        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "20000")) {
            pushApiResult.setPushSuccess(true);
            return pushApiResult;
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String apiCode = pushApiKeyParam.getApiCode();
        long timestamp = System.currentTimeMillis() / 1000;

        TreeMap<String, Object> treeMap = new TreeMap<>();
        treeMap.put("app_id", Integer.valueOf(apiCode));
        treeMap.put("timestamp", timestamp);
        treeMap.put("name", memberSourceInfo.getRealname());
        treeMap.put("mobile", memberSourceInfo.getMobile());
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        treeMap.put("city", city);
        treeMap.put("age", memberSourceInfo.getAge());
        treeMap.put("amount", JiLinZhenZeUtil.getLoan(memberSourceInfo.getLoanAmount()));
        String formattedDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        treeMap.put("apply_time", formattedDateTime);
        treeMap.put("house", JiLinZhenZeUtil.getHouse(memberSourceInfo.getHouse()));
        treeMap.put("car", JiLinZhenZeUtil.getCar(memberSourceInfo.getCar()));
        treeMap.put("policy", JiLinZhenZeUtil.getBaoXian(memberSourceInfo.getBaoxian()));
        treeMap.put("wage", 2);
        treeMap.put("funds", JiLinZhenZeUtil.getFund(memberSourceInfo.getGjj()));
        treeMap.put("insurance", JiLinZhenZeUtil.getSocial(memberSourceInfo.getShebao()));
        treeMap.put("credit", JiLinZhenZeUtil.getYuQi(memberSourceInfo.getYuqi()));
        treeMap.put("unique_id", UUID.randomUUID().toString());

        String sign = SecureUtil.md5(joinKeyValueString(treeMap) + apiSecret).toUpperCase();

        treeMap.put("sign",sign);

        log.info("【吉林震泽】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(treeMap));
        String result = HttpUtil.createPost(requestUrl)
                .body(JSON.toJSONString(treeMap))
                .execute().body();
        log.info("【吉林震泽】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(treeMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "20000")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    /**
     * 字段拼接
     *
     * @param treeMap 排序后的请求参数
     * @return 字符串
     * @date 2024/3/1
     */
    private static String joinKeyValueString(Map<String, Object> treeMap) {
        if (treeMap == null || treeMap.size() == 0) {
            return StringUtils.EMPTY;
        }
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> paramKeyAndValue : treeMap.entrySet()) {
            builder.append(paramKeyAndValue.getKey()).append(paramKeyAndValue.getValue());
        }
        return SecureUtil.md5(builder.toString());
    }






}
